package imessage

import (
	"sync"
)

type Router struct {
	sessions map[string]*Session
	sids     map[string]*Session
	lock     sync.Mutex
}

func new_router() *Router {
	return &Router{sessions: make(map[string]*Session), sids: make(map[string]*Session)}
}

func (r *Router) AddSession(session *Session) {
	r.lock.Lock()
	defer r.lock.Unlock()
	r.sids[session.sid] = session
	r.sessions[session.member] = session
}

func (r *Router) RemoveSession(sid string) {
	r.lock.Lock()
	defer r.lock.Unlock()
	delete(r.sids, sid)
}

func (r *Router) FindSessionWithSid(sid string) *Session {
	r.lock.Lock()
	defer r.lock.Unlock()
	return r.sids[sid]
}

func (r *Router) FindSessionWithMember(member string) *Session {
	r.lock.Lock()
	defer r.lock.Unlock()
	return r.sessions[member]
}

func (r *Router) Forward(msg *Message) error {
	r.lock.Lock()
	defer r.lock.Unlock()
	to := r.sessions[msg.To]
	to.channel <- msg
	return nil
}
